from channels.generic.websocket import AsyncWebsocketConsumer
import json
from django.conf import settings
from django.core.cache import cache
from channels.exceptions import StopConsumer
from .models import BasicDate
from channels.db import database_sync_to_async
class Allnums(AsyncWebsocketConsumer):
    async def websocket_connect(self, message):
        await self.accept()
    async def send_to_all(self,openid):
        li = cache.get('linenums')
        wk = cache.get('worknums')
        qu = cache.get('quans')
        us = cache.get(openid)
        code = -1
        stepNum = 1
        if type(li) != list:
            li = []
            cache.set('linenums',[],24*60*60)
        if type(wk) != list:
            wk = []
            cache.set('worknums',[],24*60*60)
        if type(qu) != list:
            def DB_get_nums():
                return BasicDate.objects.all()[0].NUMS
            qu = await database_sync_to_async(DB_get_nums)()
        else:
            qu = len(qu)
        if type(us) != list:
            us = False
        else:
            code = us[0]
            stepNum = us[2]
            us = us[1]

        await self.send(text_data=json.dumps({
            'ret':"F1",
            'linenum': len(li),
            'worknum': len(wk),
            'synum':qu,
            'st':us,
            'code':code,
            'stepNum':stepNum}))

    async def send_to_one(self,openid):
        user_channel_name = f'user_{openid}'
        await self.channel_layer.send(user_channel_name,{'type': 'send_message','message': 'QD'})

    async def secret_communication(self,event):
        await self.send(text_data=json.dumps({
            'linenum':event['linenum'],
            'worknum':event['worknum'],
            'synum': event['synum'],
            'st':event['st'],
            'code':event['code']

            }))
    async def websocket_receive(self, message):
        print(message)
        data =json.loads(message['text'])
        print(data)
        event = data['event']
        if event == "qiandao":
            await self.send_linenum()
        elif event == "getnum":
            await self.send_to_all(data['openid'])
        elif event == "work":
            await self.send_worknum()
        elif event == 'QD':
            await self.send_to_one(data['openid'])
        elif event == "bind":
            openid = data['openid']
            await self.channel_layer.group_add(f'user_{openid}',self.channel_name)

        #msg = json.dumps({"linenum":12,"worknum":12})
        #await self.send(text_data=msg)
    async def websocket_disconnect(self, message):
        raise StopConsumer()
